package com.w4cms.controller.admin;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.w4cms.core.Consts;
import com.w4cms.interceptor.AdminInterceptor;
import com.w4cms.model.Article;
import com.w4cms.model.Category;
import com.w4cms.model.SysUser;
import com.w4cms.model.TreeData;
import com.w4cms.utils.Tools;
@ControllerBind(controllerKey="/admin/article",viewPath="admin/article")
@Before(AdminInterceptor.class)
public class ArticleController extends Controller {

	public void list(){
		this.search();
	}
	public void add(){
		List<TreeData> list = Category.dao.cateTree(null);
		setAttr("list", list);
		render("articleinfo.html");
	}
	public void edit(){
		Object id = getPara();
		List<TreeData> list = Category.dao.cateTree(null);
		setAttr("list", list);
		Article m = Article.dao.findById(id);
		setAttr("obj", m);
		render("articleinfo.html");
	}
	public void save(){
		String id = getPara("id");
		boolean isOk = false;
		SysUser u = (SysUser) getSession().getAttribute(Consts.SESSION_USER);
		if(Tools.isEmpty(id)){
			isOk = new Article().set("id", UUID.randomUUID().toString()).set("title", getPara("title")).set("sub_title", getPara("sub_title")).set("user_id", u.getInt("id")).set("comefrom", getPara("comefrom"))
					.set("content", getPara("content")).set("category_id", getPara("category_id")).set("create_time", new Date()).set("update_time", new Date()).save();
		}else{
			isOk = new Article().set("id", UUID.randomUUID().toString()).set("title", getPara("title")).set("sub_title", getPara("sub_title")).set("user_id", u.getInt("id")).set("comefrom", getPara("comefrom"))
					.set("content", getPara("content")).set("category_id", getPara("category_id")).set("update_time", new Date()).save();
		}
		if(isOk){
			renderJson("success",true);
		}else{
			renderJson("msg","操作失败.");
		}
	}
	
	public void delete(){
		Object id= getPara();
		boolean isOk = Article.dao.deleteById(id);
		if(isOk){
			renderText("true");
		}else{
			renderText("删除失败.");
		}
	}
	
	public void search(){
		String search = getPara("search");
		String cateId = getPara("cateId");
		Integer pageNumber = getParaToInt("p",1);
		if(pageNumber<1){
			pageNumber=1;
		}
		Integer pageSize = getParaToInt("r",15);
		if(pageSize<1 || pageSize>100){
			pageSize = 15;
		}
		List<TreeData> cateList = Category.dao.cateTree(null);
		setAttr("cateList", cateList);
		Page<Article> list = Article.dao.searchArticles(pageNumber,pageSize,search,cateId);
		setAttr("list", list);
		keepPara();
		render("articlelist.html");
	}
}
